<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/10
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;

use ImiApp\ApiServer\Api\Model\Goodscate;
use ImiApp\ApiServer\Api\Model\Goodsbrand;


/**
 * 店铺
 * @Auth(name="token",nologin={"no"})
 * @Controller("/store.store/")
 */
class Store extends StoreOwner
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];


    // public function _initialize()
    // {
    //     parent::_initialize();
    //     // $this->store = $this->getStoreByUserId();
    //     // $this->store_id = $this->getStoreId();
    // }

    /**
     * 获取店铺信息
     *
     * @return void
     * @Action
     */
    public function get_store_data()
    {
        $this->init();
        $store = Db::name('store')->where('id', '=', $this->store_id)->select()->get();
        $store = $this->SelfChangeStoreData($store);

        $goodsbrand_apply = Db::name('goodsbrand_apply')->where('store_id', '=', $this->store_id)->orderRaw('id desc')->select()->getArray();
        if ($goodsbrand_apply) {
            foreach ($goodsbrand_apply as $key => &$g) {
                $g['date'] = date('Y-m-d', $g['createtime']);
            }
        }
        $store['goodsbrand_apply'] = $goodsbrand_apply;
        if ($store['goodsbrand_ids']) {
            $goodsbrand_list = Db::name('goodsbrand')->whereIn('id', explode(',', $store['goodsbrand_ids']))->select()->getArray();
            if ($goodsbrand_list) {
                foreach ($goodsbrand_list as $key => &$goodsbrand) {
                    // return $this->error('goods',$goodsbrand);
                    $goodsbrand['cate'] = $this->GetGoodsCateArray($goodsbrand['goodscate_id']);
                }
            }
            $store['goodsbrand'] = $goodsbrand_list;
        }

        $store['expire_date'] = date('Y-m-d', $store['expire_time']);

        return $this->success('store', $store);
    }



    protected function GetGoodsCateArray($id)
    {
        $goodscate = Db::name('goodscate')->where('id', '=', $id)->find();
        if ($goodscate['level'] != '1') {
            $goodscate2 = Db::name('goodscate')->where('id', '=', $goodscate['pid'])->find();
            $goodscate2['goodscate'] =  $goodscate;
            return $goodscate2;
        }

        return $goodscate;
    }

    /**
     * 店铺获取我的app列表
     *
     * @return void
     * @Action
     */
    public function my_app()
    {
        $this->init();
        return $this->success('', $this->GetStoreSetmod($this->store_id, $this->store->set_id));
    }

    /**
     * 获取更换辅导员评论类型列表
     *
     * @return void
     * @Action
     */
    public function get_coachcommenttype_list()
    {
        return $this->success('', Db::name('coachcommenttype')->where('id', '>=', 1)->orderRaw('id asc')->select()->getArray());
    }


    /**
     * 申请更换辅导员
     *
     * @param string $ps 申请理由
     * @param string $coachcommenttype_ids 评论类型
     * @param int $level 评论等级
     * @return void
     * @Action
     */
    public function apply_change_coach($ps = 3, $coachcommenttype_ids = null, $level = null)
    {
        $this->init();
        $data['user_id'] = $this->auth->user()->id;
        $data['store_id'] = $this->store_id;

        $count = Db::name('change_coach')->whereEx($data)->where('status', '=', '2')->where('year', '=', date('Y'))->count();
        if ($count >= 3) {
            return $this->error('您今年已经申请过3次,不能再申请');
        }


        $data['status'] = '1'; //状态:1=待审核,2=已同意,3=已拒绝
        $res = Db::name('change_coach')->whereEx($data)->find();
        if ($res) {
            return $this->error('您已申请过,请等待审核');
        }

        $data['coachcommenttype_ids'] = $coachcommenttype_ids;
        if ($coachcommenttype_ids)
            $data['str'] = implode(',', Db::name('coachcommenttype')->where('id', 'in', explode(',', $coachcommenttype_ids))->column('name'));
        $data['level'] = $level;

        $data['time'] = time();
        $data['ps'] = $ps;
        $data['year'] = date('Y');
        $data['old_pid'] = $this->store->pid;
        $res = Db::name('change_coach')->insert($data);
        if ($res) {
            return $this->success('申请成功,等待审核');
        } else {
            return $this->error('申请失败');
        }
    }


    /**
     * 撤销更换辅导员
     *
     * @return void
     * @Action
     */
    public function revoke_change_coach()
    {
        $this->init();
        $data['user_id'] = $this->auth->user()->id;
        $data['store_id'] = $this->store_id;
        $data['status'] = '1'; //状态:1=待审核,2=已同意,3=已拒绝
        $res = Db::name('change_coach')->whereEx($data)->find();
        if (!$res) {
            return $this->error('没有申请中的数据');
        }

        $res = Db::name('change_coach')->whereEx($data)->delete();
        if ($res) {
            return $this->success('您已撤销');
        }
    }


    /**
     * 店铺获取辅导员信息
     *
     * @return void
     * @Action
     */
    public function get_coach_data()
    {
        $this->init();
        $user = Db::name('user')->where('id', '=', $this->store->pid)->fieldRaw('name,mobile,invite_code,qr,set_id,avatar')->find();
        if ($user) {
            $user['set'] = Db::name('set')->where('id', '=', $user['set_id'])->value('name');
        }
        $data['store_id'] = $this->store_id;
        $change_coach = Db::name('change_coach')->whereEx($data)->orderRaw('id desc')->find();
        $refuse = Db::name('change_coach')->whereEx($data)->where('status', '=', '3')->orderRaw('id desc')->find();
        return $this->success($this->store->pid, ['user' => $user, 'change_coach' => $change_coach, 'refuse' => $refuse]);
    }


    /**
     * 支付店铺认证
     *
     * @param integer $pay_type 支付类型:1=微信,2=支付宝,3=钱包,9=其他
     * @param string $pay_password 支付密码
     * @return void
     * @Action
     */
    public function pay_store_ca_order($pay_type = 3, $pay_password = null)
    {
        $this->init();
        switch ($pay_type) {
            case '3':
                //验证密码 
                // $this->VerifyStorePayPassword($this->store_id,$pay_password);
                $password = $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
                if ($password != 'ok') {
                    return $this->error('支付密码错误', null, CODE_用户支付密码错误);
                }
                break;

            default:
                break;
        }
        $res = Db::name('store_caorder')->where('store_id', '=', $this->store_id)->where('pay_status', '=', '2')->select()->get();
        if ($res) {
            return $this->error('您已支付过', $res);
        }
        $store_caorder = Db::name('store_caorder')->where('store_id', '=', $this->store_id)->where('pay_status', '=', '1')->select()->get(); //支付状态:1=待支付,2=已支付,3=已退款,4=已超时
        //创建支付订单
        if ($store_caorder) {
            //
            $this->PayStoreCaorder($store_caorder, $pay_type);
        } else {
            return $this->error('没有认证订单');
        }
    }









    /**
     * 支付续费认证
     *
     * @param integer $pay_type 支付类型:1=微信,2=支付宝,3=钱包,9=其他
     * @param string $pay_password 支付密码
     * @return void
     * @Action
     */
    public function keep_store_ca_order($pay_type = 3, $pay_password = null)
    {
        $this->init();
        switch ($pay_type) {
            case '3':
                //验证密码 
                // $this->VerifyStorePayPassword($this->store_id,$pay_password);//店铺密码取消
                // $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
                break;

            default:
                break;
        }
        $store_caorder = Db::name('store_caorder')->where('store_id', '=', $this->store_id)->where('num', '>', 1)->where('pay_status', '=', '1')->select()->get(); //支付状态:1=待支付,2=已支付,3=已退款,4=已超时
        //创建支付订单
        if ($store_caorder) {
            //
            $this->KeepPayStoreCaorder($store_caorder, $pay_type);
        } else {


            $in_data['store_id'] = $this->store_id;
            $in_data['user_id'] = $this->auth->user()->id;
            $in_data['pay_status'] = '1'; //支付状态:1=待支付,2=已支付,3=已退款,4=已超时
            // $res = Db::name('store_caorder')->whereEx($in_data)->select()->get();

            // if (!$res) {
            $in_data['money'] = $this->getKeepStorePrice($this->store->ltd_status, $this->store->set_id);
            $in_data['price'] = $this->getKeepStorePrice($this->store->ltd_status, $this->store->set_id);
            $in_data['num'] = Db::name('store_caorder')->where('store_id', '=', $this->store_id)->where('pay_status', '=', '2')->count() + 1;

            $in_data['order'] = $this->rand_order('Cak', 28);
            $in_data['time'] = time();
            $in_data['ps']  = '续费认证店铺';
            $in_data['get_status'] = '1'; //获取方式:1=购买,2=领取
            $in_data['id'] = Db::name('store_caorder')->insert($in_data)->getLastInsertId();
            // }
            $this->KeepPayStoreCaorder($in_data, $pay_type);
        }
    }


    /**
     * 退活动保证金
     *
     * @param string $pay_password 支付密码
     * @param string $money 退金额
     * @param string $status 类型:1=普通保证金,2=活动保证金
     * @return void
     * @Action
     */
    public function refund_store_surety(?string $pay_password = null, ?float $money = 0, ?string $status = '1')
    {
        $this->init();

        if ($status == '1') {
            $field = 'surety';
            $ps = '退保证金';
            $type_id = CODE_店铺退保证金;
        } else {
            $field = 'act_surety';
            $ps = '退保活动证金';
            $type_id = CODE_店铺退活动保证金;
        }

        if ($this->store->$field < $money) {
            return $this->error('保证金不足');
        }
        $this->DecStoreSurety($this->store_id,  $money, $ps, $ps, 0, $field);
        $this->IncStoreMoney($this->store_id, $money, $ps, $type_id, 0);
        return $this->success('退保证金成功');
    }

    /**
     * 支付店铺保证金或活动保证金
     *
     * @param integer $pay_type 支付类型:1=微信,2=支付宝,3=钱包,9=其他
     * @param string $pay_password 支付密码
     * @param string $status 类型:1=普通保证金,2=活动保证金
     * @param string $money 充值金额(第1次后才有效)
     * @return void
     * @Action
     */
    public function pay_store_surety_order($pay_type = 3, ?string $pay_password = null, ?float $money = 0, ?string $status = '1')
    {

        var_dump('status'.$status.'————————————————————————充值金额💰💰💰💰💰💰💰💰',$money);
        // $this->error($money);


        $this->init();
        switch ($pay_type) {
            case '3':
                //验证密码 
                // $this->VerifyStorePayPassword($this->store_id,$pay_password);
                $res = $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
                if ($res != 'ok') {
                    return $this->error('支付密码错误', null, CODE_用户支付密码错误);
                }
                break;

            default:
                break;
        }

        if (!$status)
            $status = '1';
        $where['status'] = $status;
        // $this->error($status);

        //第一次保证金固定
        $res = Db::name('store_surety_order')->whereEx($where)->where('store_id', '=', $this->store_id)->where('pay_status', '=', '2')->find();

        if ($res) {
            // return $this->error('您已支付过', $res);
            if ($money < 0.01) {
                return $this->error('请输入支付金额');
            }
        } else {
            //获取店铺需要缴纳的保证金

            switch ($status) {
                case '1':
                    $money = $this->GetStoreSuretyMoney($this->store->set_id);
                    break;

                case '2':
                    $money = $this->GetStoreSuretyMoney($this->store->set_id);
                    break;
                default:
                    # code...
                    break;
            }
        }

        //这里只是金额

        $store_surety_order = Db::name('store_surety_order')->whereEx($where)->where('store_id', '=', $this->store_id)->where('pay_status', '=', '1')->select()->get(); //支付状态:1=待支付,2=已支付,3=已退款,4=已超时

        //创建支付订单
        if ($store_surety_order) {
            //
            $this->PayStoreSuretyorder($store_surety_order, $pay_type, $status);
        } else {
            //没有就创建订单

            $in_data['store_id'] = $this->store_id;
            $in_data['user_id'] = $this->auth->user()->id;
            $in_data['pay_status'] = '1'; //支付状态:1=待支付,2=已支付,3=已退款,4=已超时
            // $res = Db::name('store_caorder')->whereEx($in_data)->select()->get();

            // if (!$res) {
            $in_data['money'] = $money;
            $in_data['price'] = $money;
            var_dump('充值保证金',$where);
            $in_data['status']  = $status;
            $in_data['num'] = Db::name('store_surety_order')->whereEx($where)->where('store_id', '=', $this->store_id)->where('pay_status', '=', '2')->count() + 1;

            $in_data['order'] = $this->rand_order('Surety', 28);
            $in_data['time'] = time();
            switch ($status) {
                case '1':
                    $in_data['ps']  = '店铺保证金第几次' . $in_data['num'];
                    break;
                case '2':
                    $in_data['ps']  = '店铺活动保证金第几次' . $in_data['num'];
                    break;
                default:
                    # code...
                    break;
            }

            $in_data['pay_type']  = $pay_type;
            $in_data['id'] = Db::name('store_surety_order')->insert($in_data)->getLastInsertId();
            // }
            $this->PayStoreSuretyorder($in_data, $pay_type, $status);
            // return $this->error('没有认证订单');
        }
    }



    /**
     * 申请品牌资质
     *
     * @param string $images 图集
     * @param string $name 品牌名
     * @return void
     * @Action
     */
    public function apply_goodsbrand(?string $images, ?string $name = null)
    {

        $this->init();
        //goodsbrand_apply
        $data['images'] = $images;
        $data['store_id'] = $this->store_id;

        $this->VerifyStr($images);
        // $res = Db::name('goodsbrand_apply')->whereEx($data)->select()->get();
        // if ($res) {
        //     if ($res['status'] == '2')
        //         return $this->error('已通过', $res['id']);
        //     $data['status'] = '1';
        //     $id = Db::name('goodsbrand_apply')->whereEx($data)->update($data);
        //     return $this->success('等待审核');
        // }

        // $data['uid'] = $this->auth->user()->id;
        $data['name']  = $name;
        $data['status'] = '1';
        $data['createtime'] = time();
        $id = Db::name('goodsbrand_apply')->insert($data)->getLastInsertId();
        return $this->success('等待审核', $id);
    }

    // /**
    //  * 获取店铺id
    //  *
    //  * @return void
    //  */
    // protected function getStoreId()
    // {
    //     return $this->store['id'];
    // }

    /**
     * 添加店铺公告
     *
     * @param string $name 标题
     * @param string $content 公告内容
     * @param string $images 图集
     * @return void
     * @Action
     */
    public function add_storebulletin($name = null, $content = null, $images = null)
    {

        $this->init();
        $data['name'] = $name;
        $data['content'] = $content;
        $data['images'] = $images;
        $this->VerifyStr($data);
        $data['store_id'] = $this->store_id;
        $res = Db::name('storebulletin')->whereEx($data)->select()->get();
        if ($res) {
            return $this->error('已有该内容', $res['id']);
        }

        $data['uid'] = $this->auth->user()->id;
        $data['status'] = '1';
        $data['createtime'] = time();
        $id = Db::name('storebulletin')->insert($data)->getLastInsertId();
        return $this->success('发布成功', $id);
    }


    /**
     * 获取发布的公告列表🐲
     *
     * @param integer $page 1
     * @param integer $limit 8
     * @param int $status 0=关闭,1=正常
     * @return void
     * @Action
     */
    public function get_storebulletin_list(?int $page = 1, ?int $limit = 8, $status = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 8;
        if ($status !== null && $status !== '')
            $data['status'] = $status;
        $data['store_id'] = $this->store_id;
        $list = Db::name('storebulletin')->whereEx($data)->orderRaw('createtime desc')->page($page, $limit)->select()->getArray();
        foreach ($list as $key => &$val) {
            $val['date'] = date('Y-m-d H:i', $val['createtime']);
        }
        return $this->success('ok', $list);
    }

    /**
     * 获取店铺发布的公告详情🐲
     *
     * @param int $id 公告id
     * @return void
     * @Action
     */
    public function get_storebulletin_data(?int $id = null)
    {
        $this->init();
        $data['status'] = '1';
        $data['id'] = $id;
        $data['store_id'] = $this->store_id;
        $val = Db::name('storebulletin')->whereEx($data)->select()->get();
        $val['date'] = date('Y-m-d H:i', $val['createtime']);
        return $this->success('ok', $val);
    }


    /**
     * 删除店铺的公告详情🐲
     *
     * @param int $id 公告id
     * @return void
     * @Action
     */
    public function del_storebulletin_data($id = null)
    {
        $this->init();
        $data['status'] = '1';
        $data['id'] = $id;
        $data['store_id'] = $this->store_id;
        $list = Db::name('storebulletin')->whereEx($data)->delete();
        return $this->success('删除', $list);
    }






    /**
     * 获取钱变动列表🐲
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $date 月
     * @param string $status 1=支出,2=收入
     * @param int $typestatus_id 类型
     * @return void
     * @Action
     */
    public function get_money_log_list(?string $date = null, ?int $page = 1, ?int $limit = 10, ?string $status = null, ?int  $typestatus_id = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data['store_id'] = $this->store_id;

        if ($date) {
            list($s, $e) = $this->GetMonthTime($date);
            $data['createtime'] = ['>=', $s];
            $data['and'] = ['createtime' => ['<=', $e]];
        }

        $inc = Db::name('store_money_log')->whereEx($data)->where('status', '=', '2')->sum('money');
        $dec = Db::name('store_money_log')->whereEx($data)->where('status', '=', '1')->sum('money');
        if (!$inc)
            $inc = 0;
        if (!$dec)
            $dec = 0;

        if ($status !== null && $status !== '')
            $data['status'] = $status;
        if ($typestatus_id)
            $data['typestatus_id'] = $typestatus_id;
        $list = Db::name('store_money_log')->whereEx($data)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
        foreach ($list as &$val) {
            $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        }
        $this->success('ok', ['inc' => $inc, 'dec' => $dec, 'list' => $list]);
    }

    /**
     * 获取贝壳变动列表🐲
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $date 月
     * @param string $status 1=支出,2=收入
     * @param int $typestatus_id 类型
     * @return void
     * @Action
     */
    public function get_shell_log_list(?string $date = null, ?int $page = 1, ?int $limit = 10, ?string $status = null, ?int  $typestatus_id = null)
    {
        $this->init();
        // $page = $page ?: 1;
        // $limit = $limit ?: 10;
        // if ($status !== null && $status !== '')
        //     $data['status'] = $status;
        // $data['store_id'] = $this->store_id;
        // $list = Db::name('store_shell_log')->whereEx($data)->orderRaw('createtime desc')->page($page, $limit)->select()->getArray();
        // foreach ($list as $key => &$val) {
        //     $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        // }
        // return $this->success('ok', $list);

        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data['store_id'] = $this->store_id;

        if ($date) {
            list($s, $e) = $this->GetMonthTime($date);
            $data['createtime'] = ['>=', $s];
            $data['and'] = ['createtime' => ['<=', $e]];
        }

        $inc = Db::name('store_shell_log')->whereEx($data)->where('status', '=', '2')->sum('shell');
        $dec = Db::name('store_shell_log')->whereEx($data)->where('status', '=', '1')->sum('shell');
        if (!$inc)
            $inc = 0;
        if (!$dec)
            $dec = 0;

        if ($status !== null && $status !== '')
            $data['status'] = $status;
        if ($typestatus_id)
            $data['typestatus_id'] = $typestatus_id;
        $list = Db::name('store_shell_log')->whereEx($data)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
        foreach ($list as &$val) {
            $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        }
        $transfer = Db::name('store_shell_log')->where('store_id', '=', $this->store_id)->where('typestatus_id', '=', 35)->count('shell');

        $freeze = Db::name('freeze')
            ->where('store_id', '=', $this->store_id)
            ->where('user_status', '=', 'store')
            ->where('pay_type', '=', 'shell')
            ->where('pay_status', '=', '2') //支付状态:2=已支付,3=已解冻,4=已超时
            ->sum('shell');
        $this->success('ok', ['inc' => $inc, 'dec' => $dec, 'list' => $list, 'freeze' => $freeze ? $freeze : 0, 'transfer' => $transfer ? $transfer : 0]);
    }



    /**
     * 获取积分变动列表🐲
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $date 月
     * @param string $status 1=支出,2=收入
     * @param int $typestatus_id 类型
     * @return void
     * @Action
     */
    public function get_score_log_list(?string $date = null, ?int $page = 1, ?int $limit = 10, ?string $status = null, ?int  $typestatus_id = null)
    {
        $this->init();

        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data['store_id'] = $this->store_id;

        if ($date) {
            list($s, $e) = $this->GetMonthTime($date);
            $data['createtime'] = ['>=', $s];
            $data['and'] = ['createtime' => ['<=', $e]];
        }

        $inc = Db::name('store_score_log')->whereEx($data)->where('status', '=', '2')->sum('score');
        $dec = Db::name('store_score_log')->whereEx($data)->where('status', '=', '1')->sum('score');
        if (!$inc)
            $inc = 0;
        if (!$dec)
            $dec = 0;

        if ($status !== null && $status !== '')
            $data['status'] = $status;
        if ($typestatus_id)
            $data['typestatus_id'] = $typestatus_id;
        $list = Db::name('store_score_log')->whereEx($data)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
        foreach ($list as &$val) {
            $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        }
        $transfer = Db::name('store_score_log')->where('store_id', '=', $this->store_id)->where('typestatus_id', '=', 37)->count('score');
        $freeze = Db::name('freeze')
            ->where('store_id', '=', $this->store_id)
            ->where('user_status', '=', 'store')
            ->where('pay_type', '=', 'score')
            ->where('pay_status', '=', '2') //支付状态:2=已支付,3=已解冻,4=已超时
            ->sum('score');
        $this->success('ok', ['inc' => $inc, 'dec' => $dec, 'list' => $list, 'freeze' => $freeze ? $freeze : 0, 'transfer' => $transfer ? $transfer : 0]);
    }


    /**
     * 获取提现服务费
     *
     * @Action
     */
    public function get_money_out_ratio()
    {
        $this->init();

        $ratio = $this->GetSetserverstoreVal($this->store_id, $this->store->set_id, 14); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
        return $this->success('提现服务费', $ratio);
    }


    /**
     * 获取转移贝壳服务费
     *
     * @Action
     */
    public function get_transfer_shell_ratio()
    {
        $this->init();

        $ratio = $this->GetSetserverstoreVal($this->store_id, $this->store->set_id, 13); //1=拍卖技术费%(邮寄,2=拍卖技术费%(服务,3=拼团技术费%(邮寄,4=拼团技术费%(服务,5=贝壳服务费%,6=积分服务费%,7=调货费%,8=现金服务费%(邮寄,9=现金服务费%(服务,10=立即买单%,11=保证金阀值(元),12=借米额度(M倍),13=贝壳转移服务费%,14=提现手续费%
        return $this->success('贝壳转移服务费', $ratio);
    }

    /**
     * 转移贝壳到店铺余额
     *
     * @param float $shell 贝壳
     * @param string $pay_password 支付密码
     * @return void
     * @Action
     */
    public function transfer_shell_to_money(?float $shell = null, $pay_password = null)
    {
        $this->init();

        //验证密码 
        // $this->VerifyStorePayPassword($this->store_id,$pay_password);
        $password = $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
        if ($password != 'ok') {
            return $this->error('支付密码错误', null, CODE_用户支付密码错误);
        }
        if ($this->store->shell < $shell) {
            return $this->error('贝壳不足');
        }


        $ratio = $this->GetSetserverstoreVal($this->store_id, $this->store->set_id, 13);
        $ratio = ((float)$ratio / 100);
        $服务费 = round($ratio * $shell, 2);
        $到账 = $shell - $服务费;
        $this->IncStoreMoney($this->store_id, $到账, $shell . '贝壳转余额', 35, 0);
        $this->DecStoreShell($this->store_id, $shell, '贝壳转余额', 35, 0);
        return $this->success('转移成功');
    }


    /**
     * 转移贝壳到用户贝壳
     *
     * @param float $shell 贝壳
     * @param string $pay_password 支付密码
     * @return void
     * @Action
     */
    public function transfer_shell_to_userself(?float $shell = null, $pay_password = null)
    {
        $this->init();
        //验证密码 
        // $this->VerifyStorePayPassword($this->store_id,$pay_password);
        $password = $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
        if ($password != 'ok') {
            return $this->error('支付密码错误', null, CODE_用户支付密码错误);
        }
        if ($this->store->shell < $shell) {
            return $this->error('贝壳不足');
        }




        $this->DecStoreShell($this->store_id, $shell, '店铺贝壳转自己用户贝壳', 36, 0);
        $this->IncUserShell($this->auth->user()->id, $shell, '店铺贝壳转自己用户贝壳', 36, 0);
        return $this->success('转移成功');
    }




    /**
     * 转移积分到用户积分
     *
     * @param float $score 积分
     * @param string $pay_password 支付密码
     * @return void
     * @Action
     */
    public function transfer_score_to_userself(?float $score = null, $pay_password = null)
    {
        $this->init();
        //验证密码 
        // $this->VerifyStorePayPassword($this->store_id,$pay_password);
        $password = $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
        if ($password != 'ok') {
            return $this->error('支付密码错误', null, CODE_用户支付密码错误);
        }
        if ($this->store->score < $score) {
            return $this->error('积分不足');
        }




        $this->DecStoreScore($this->store_id, $score, '店铺积分转自己用户积分', 37, 0);
        $this->IncUserScore($this->auth->user()->id, $score, '店铺积分转自己用户积分', 37, 0);
        return $this->success('转移成功');
    }

    /**
     * 转移余额到用户余额
     *
     * @param float $money 余额
     * @param string $pay_password 支付密码
     * @return void
     * @Action
     */
    public function transfer_money_to_userself(?float $money = null, $pay_password = null)
    {
        $this->init();
        //验证密码 
        // $this->VerifyStorePayPassword($this->store_id,$pay_password);
        $password = $this->VerifyUserPayPassword($this->auth->user()->id, $pay_password);
        if ($password != 'ok') {
            return $this->error('支付密码错误', null, CODE_用户支付密码错误);
        }
        if ($this->store->money < $money) {
            return $this->error('余额不足');
        }




        $this->DecStoreMoney($this->store_id, $money, '店铺余额转自己用户余额', 38, 0);
        $this->IncUserMoney($this->auth->user()->id, $money, '店铺余额转自己用户余额', 38, 0);
        return $this->success('转移成功');
    }


    /**
     * 获取保证金变动列表🐲
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $date 月
     * @param string $status 1=支出,2=收入
     * @param string $type_status 类型:act_surety=活动保证金,surety=保证金
     * @return void
     * @Action
     */
    public function get_surety_log_list(?string $date = null, ?int $page = 1, ?int $limit = 10, ?string $status = null,  ?string $type_status = null)
    {
        $this->init();

        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data['store_id'] = $this->store_id;

        if ($date) {
            list($s, $e) = $this->GetMonthTime($date);
            $data['createtime'] = ['>=', $s];
            $data['and'] = ['createtime' => ['<=', $e]];
        }
        if ($type_status)
            $data['type_status'] = $type_status;

        $inc = Db::name('store_surety_log')->whereEx($data)->where('status', '=', '2')->sum('surety');
        $inc = $inc + (float)Db::name('store_surety_log')->whereEx($data)->where('status', '=', '2')->sum('act_surety');

        $dec = Db::name('store_surety_log')->whereEx($data)->where('status', '=', '1')->sum('surety');
        var_dump('dec', $dec);
        $dec = $dec + (float)Db::name('store_surety_log')->whereEx($data)->where('status', '=', '1')->sum('act_surety');

        var_dump('dec', $dec);
        if (!$inc)
            $inc = 0;
        if (!$dec)
            $dec = 0;

        if ($status !== null && $status !== '')
            $data['status'] = $status;

        $list = Db::name('store_surety_log')->whereEx($data)->orderRaw('id desc')->page($page, $limit)->select()->getArray();
        foreach ($list as &$val) {
            $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        }

        $freeze = Db::name('freeze')
            ->where('store_id', '=', $this->store_id)
            ->where('user_status', '=', 'store')
            ->where('pay_type', '=', $type_status)
            ->where('pay_status', '=', '2') //支付状态:2=已支付,3=已解冻,4=已超时
            ->sum('surety');
        $this->success('ok', ['inc' => $inc, 'dec' => $dec, 'list' => $list, 'freeze' => $freeze ? $freeze : 0]);
    }


    /**
     * 添加店铺文件大小
     *
     * @param string $url 文件路径
     * @param int $size 文件大小
     * @return void
     * @Action
     */
    public function add_file_size($url = null, $size = null)
    {
        $this->init();

        $res = Db::name('attachment')->where('url', '=', $url)->select()->get();

        if ($size < 0) {
            return $this->erorr('大小错误', '就知道你想到这样了,所以限制了的');
        }
        $kb = round($size / 1024, 2);
        //判断大小
        if (($this->store->filesize + $kb) > $this->store->now_filesize)
            return $this->error('您的店铺相册空间不足 请优化图片或视频', $this->store->now_filesize / 1024, CODE_店铺网盘储存不足);
        if (!$res) {
            $data['url'] = $url;
            $data['store_id'] = (int)$this->store_id;
            $data['user_id'] = (int)$this->auth->user()->id;
            $data['createtime'] = time();
            $data['admin_id'] = 0;
            $data['filesize'] = $size;
            $data['storage'] = 'obs';
            Db::name('attachment')->insert($data);
            //添加文件大小

            Db::name('store')->where('id', '=', $this->store_id)->setFieldInc('filesize', $kb)->update();
        }
        $store  = Db::name('store')->where('id', '=', $this->store_id)->find();
        return $this->success('', ($store['now_filesize'] - $store['filesize']));
    }


    /**
     * 获取obs文件大小
     *
     * @param string $url 文件路径
     * @return void
     * @Action
     */
    public function get_obs_file_size($url = null)
    {
        $this->init();



        if (strpos($url, 'http') === false)
            $url = 'http://obs.pddds.cn/' . $url;

        $kb = 0;
        $resp = get_headers($url);
        if (isset($resp['Content-Length'])) {
            $kb = round($resp['Content-Length'] / 1024, 2);
        }
        return $kb;
    }



    /**
     * 删除店铺文件大小
     *
     * @param string $url 文件路径
     * @return void
     * @Action
     */
    public function del_file_size($url = null)
    {
        $this->init();
        $msg = '删除成功';
        $res = Db::name('attachment')
            ->where('url', '=', $url)
            ->where('store_id', '=', $this->store_id)
            ->whereIsNull('deletetime')
            ->select()->get();

        if ($res) {
            Db::name('attachment')->where('id', '=', $res['id'])->update(['deletetime' => time()]); //删除该文件 加入对列 1天后查询数据库是否有该文件内容

            $queue = \Imi\Queue\Facade\Queue::getQueue('del_obs_file');
            $message = new \Imi\Queue\Model\Message;
            //发布删除队列文件

            $message->setMessage($url);
            $queue->push($message);
            $size = round($res['filesize'] / 1024, 2);
            //添加文件大小
            Db::name('store')->where('id', '=', $this->store_id)->setFieldDec('filesize', $size)->update();
        } else {
            $msg = '没找到该文件或已删除';
        }
        $store  = Db::name('store')->where('id', '=', $this->store_id)->find();
        return $this->success($msg, ($store['now_filesize'] - $store['filesize']));
    }



    /**
     * 获取店铺二维码
     *
     * @return void
     * @Action
     */
    public function get_store_qr()
    {
        $this->init();
        if (!$this->store->qr) {
            $this->store->qr = $this->UpdateStoreQrCode($this->store->id);
            // $this->store->qr = $this->GetStoreQrcode($this->store_id);
            // $this->store->save();
        }

        return $this->success('qr', $this->store->qr);
    }

    // /**
    //  * 评论通知
    //  *
    //  * @param int $notice_id 通知id
    //  * @param string $content 内容
    //  * @param string $images 图集(可不传)
    //  * @param int $comment_id 评论id(可不传)
    //  * @return void
    //  */
    // public function add_comment($notice_id, $content = null, $comment_id = null, $images = null)
    // {
    //     $val = Db::name('notice')->where('id', $notice_id)->select()->get();
    //     if (!$val) {
    //         return $this->error('该通知不存在');
    //     }
    //     $where['notice_id'] = $notice_id;
    //     $this->VerifyStr($content);
    //     if ($comment_id) {

    //         $res = Db::name('notice_comment')->where('id', $comment_id)->whereEx($where)->select()->get();
    //         if (!$res) {
    //             return $this->error('该评论不存在');
    //         }
    //         if ($res['comment_id'] > 0) {
    //             $where['top_id'] = $res['top_id'];
    //         } else {
    //             $where['top_id'] = $comment_id;
    //         }
    //         $where['comment_uid'] = $res['uid']; //被评论的用户id
    //         // $where['top_status'] = '2';
    //     } else {
    //         // $where['top_status'] = '1';
    //     }
    //     $where['comment_id'] = $comment_id;

    //     $where['content'] = $content;
    //     $where['images'] = $images;
    //     $where['uid'] = $this->auth->user()->id;
    //     $where['time'] = time();
    //     $where['switch'] = 0; //默认都要后台审核
    //     $id = Db::name('notice_comment')->insertGetId($where);

    //     // $this->AddMsg($uid,$status,$public_id,$user_id=null,$title=null);//类型:1=通知点赞,2=通知评论,3=提问点赞,4=提问评论,5=活动点赞,6=活动留言,7=聊天消息
    //     if ($comment_id) {
    //         if ($res['uid'] != $this->auth->user()->id) //自己评论自己不添加
    //             $this->AddMsg($res['uid'], 2, $notice_id, $this->auth->user()->id, $this->auth->nickname . '给你通知评论了');
    //     } else {
    //         // if ($val['uid'] != $this->auth->user()->id) //自己评论自己不添加
    //         // $this->AddMsg($val['uid'], 2, $notice_id, $this->auth->user()->id, $this->auth->nickname . '给你通知评论了');
    //     }



    //     return $this->success('评论成功', $id);
    // }

    // /**
    //  * 获取通知列表
    //  * @param string $search 搜索内容
    //  * @param integer $page 1
    //  * @param integer $limit 10
    //  * @return void
    //  */
    // public function get_list($search = null, $page = 1, $limit = 3)
    // {

    //     if ($this->isStore()) {
    //         $where['notice_status'] = '1'; //公告类型:1=店铺,2=用户
    //     } else {
    //         $where['notice_status'] = '2'; //公告类型:1=店铺,2=用户
    //     }
    //     if($search){
    //         $where['content|name'] = ['like',"%".$search."%"];
    //     }
    //     $where['status'] = '1'; //公告状态:0=关闭,1=正常
    //     $list = Db::name('notice')
    //         ->whereEx($where)
    //         ->orderRaw('createtime desc')
    //         ->page($page, $limit)
    //         ->select()->getArray();
    //     return $this->success($page, $list);
    // }

    // /**
    //  * 获取通知详情
    //  *
    //  * @param int $id 通知id
    //  * @return void
    //  */
    // public function get_data($id = null)
    // {
    //     // if ($this->isStore()) {
    //     //     $where['notice_status'] = '1'; //公告类型:1=店铺,2=用户
    //     // } else {
    //     //     $where['notice_status'] = '2'; //公告类型:1=店铺,2=用户
    //     // }
    //     $where['status'] = '1'; //公告状态:0=关闭,1=正常
    //     $where['id'] = $id;
    //     $notice = Db::name('notice')
    //         ->whereEx($where)
    //         ->select()->get();
    //     if (!$notice) {
    //         return $this->error('没有该通知');
    //     }

    //     $this->AddViews($id);
    //     $this->ChangeFieldData($notice);

    //     return $this->success($id, $notice);
    // }




    /**
     * 获取商品分类列表
     * @param int $pid 上级id
     * @param string $name 搜索名
     * @return void
     * @Action
     */
    public function get_goodscate($pid = null, $name = null)
    {
        $this->init();
        $this->model = Goodscate::dbQuery();
        // if(!$level){
        //     $level = 0;
        //     $list = $this->model->with('children.children.children')->where('pid', $level)->orderRaw('weigh desc, id asc')->select()->getArray();
        // }else{

        // }
        //$this->store->goodscate_ids
        $where = [];
        if ($name)
            $where['name'] = ['like', '%' . $name . '%'];
        if ($pid) {

            // $where['pid'] = $pid;
            // halt($where);
            $list = $this->model->where('pid', '=', $pid)->whereEx($where)->whereIn('pid',   explode(',', $this->store->goodscate_ids))->orderRaw('weigh desc, id asc')->select()->getArray();
        } else {
            // var_dump($where);
            $list = $this->model->whereIn('pid',   explode(',', $this->store->goodscate_ids))->whereEx($where)->orderRaw('weigh desc, id asc')->select()->getArray();
        }
        return $this->success('分类', $list);
    }


    /**
     * 获取商品主分类列表
     * @param int $pid 上级id
     * @param string $name 搜索名
     * @return void
     * @Action
     */
    public function get_goodscate1($pid = null, $name = null)
    {
        $this->init();
        $this->model = Goodscate::dbQuery();

        $where = [];
        if ($name)
            $where['name'] = ['like', '%' . $name . '%'];
        if ($pid) {
            $list = $this->model->where('pid', '=', $pid)->whereEx($where)->whereIn('pid',   explode(',', $this->store->goodscate_ids))->orderRaw('weigh desc, id asc')->select()->getArray();
        } else {
            // var_dump($where);
            $list = $this->model->whereIn('id',  explode(',', $this->store->goodscate_ids))->whereEx($where)->orderRaw('weigh desc, id asc')->select()->getArray();
        }
        return $this->success('分类', $list);
    }



    /**
     * 获取商品分类下品牌列表
     *
     * @param int $goodscate_id 商品分类
     * @return void
     * @Action
     */
    public function get_goodsbrand($goodscate_id = null)
    {

        $this->init();
        // $res = $this->model->where('id',$goodscate_id)->where('pid','in',$this->store->goodscate_ids)->select()->get();
        // if(!$res){
        //     return $this->error('没有该分类权限');
        // }
        if ($goodscate_id) {
            $this->modelcate = Goodscate::dbQuery();
            $goodscate = $this->modelcate->where('id', '=', $goodscate_id)->select()->get();
            if (!$goodscate) {
                return $this->error('没有该商品分类');
            }
            if ($goodscate['level'] != 2) {
                return $this->error('请传递二级分类');
            }

            $this->model = Goodsbrand::dbQuery();
            $list = $this->model->where('goodscate_id', '=', $goodscate_id)->where('status', '=', 'up')->orderRaw('weigh desc, id asc')->select()->getArray();
        } else {
            $this->model = Goodsbrand::dbQuery();
            $list = $this->model->where('status', '=', 'up')->orderRaw('weigh desc, id asc')->select()->getArray();
        }

        return $this->success('品牌', $list);
    }

    /**
     * 修改支付密码
     *
     * @param string $pay_password
     * @param string $captcha
     * @Action
     * @return void
     */
    public function update_pay_password($pay_password, $captcha)
    {


        if (strlen($pay_password) > 5) {
            $data['pay_password'] = md5($pay_password);
            $store = Db::name('store')->where('id', '=', $this->store_id)->update($data);
            return $this->success('修改密码成功');
        } else {
            return $this->error('密码长度不足');
        }
    }



    /**
     * 编辑店铺
     *
     * @param string $logo_image LOGO
     * @param string $sign 签名
     * @param string $banner_image banner图片
     * @param string $content 店铺内容
     * @param string $remark 备注
     * @param string $mobile 联系人手机号
     * @param string $addr 地址
     * @param string $work_time 营业时间
     * @param string $lat 纬度
     * @param string $lng 经度
     * @param string $wechat 微信号
     * @param string $work_date 营业日期
     * @param string $qualification_images 资质图
     * @param string $close_status 关闭状态:1=未关闭,2=关闭
     * @param string $city_switch 同城线下 1=支持,0=不支持
     * @param string $area_id 地区id
     * @return void
     * @Action
     */
    public function edit_store(
        $qualification_images = null,
        $logo_image = null,
        $sign = null,
        $banner_image = null,
        $content = null,
        $remark = null,
        $mobile = null,
        $addr = null,
        $work_time = null,
        $lat = null,
        $lng = null,
        $wechat = null,
        $work_date = null,
        $close_status = null,
        $city_switch = null,
        $area_id  = null
    ) {
        $this->init();
        $param = $this->request->param();
        // 判断是否已经实名认证了
        // $this->VerifyRealName();



        $data = $this->edit_storeSelf($param);
        $this->UpdateStoreGeo($this->store_id);
        return $this->success('修改成功', $param);
    }

    /**
     * 编辑店铺
     *
     * @param array $param 参数
     * @return void
     */
    protected function edit_storeSelf($param)
    {
        $fields = [
            'qualification_images', 'logo_image', 'sign', 'banner_image', 'content',  'remark',  'mobile', 'addr', 'work_time', 'lat', 'lng', 'wechat', 'work_date', 'close_status', 'city_switch', 'area_id'
        ];
        $data = get_field_arr($param, $fields);
        if (isset($data['area_id'])) {
            $area = $this->GetAreaAllData($data['area_id']);
            // $data[''] = $area['']
        }

        $data['updatetime'] = time();
        Db::name('store')->where('id', '=', $this->store_id)->update($data);
        return $data;
    }

    /**
     * 获取店铺一些配置
     * @param string $field 字段值
     * @return void
     * @Action
     */
    public function get_storeallset(?string $field = null)
    {
        $this->init();
        $where['set_id'] = $this->store->set_id;
        if ($field) {
            $arr = [
                'set_id',
                'storeallset1',
                'storeallset2',
                'storeallset3',
                'storeallset4',
                'storeallset5',
                'storeallset6',
                'storeallset7',
                'storeallset8',
                'name',
                'val'
            ];
            if (!in_array($field, $arr))
                return $this->error('没有该字段');
            $res = Db::name('storeallsetlist')->whereEx($where)->value($field);

            $str = [
                'set_id' => '类型id',
                'storeallset1' => '晋级条件(订单量)',
                'storeallset2' => '晋级条件(交易额)',
                'storeallset3' => '入驻积分奖励',
                'storeallset4' => '入驻费(元)',
                'storeallset5' => '次年续费',
                'storeallset6' => '店铺保证金(元)',
                'storeallset7' => '店铺晋升(元)',
                'storeallset8' => '网盘容量',
                'name' => '类型名',
                'val' => '设置'
            ];

            $name = $str[$field];
        } else {
            $res = Db::name('storeallsetlist')->whereEx($where)->find();
            $name = '列表';
        }


        return $this->success($name, $res);
    }
}
